package controllers

import (
	"AcServer/src/configration"
	"AcServer/src/models"
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"strings"
	"time"
)

var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
	//保存消息到数据库
	if strings.HasPrefix(msg.Topic(), "autoclock/device_list/") {
		var device models.Device
		err := json.Unmarshal(msg.Payload(), &device)
		if err != nil {
			fmt.Printf("mqtt json Unmarshal device error : %s", err)
			return
		}
		o := orm.NewOrm()
		_, err = o.Insert(&device)
		if err != nil {
			fmt.Printf("mqtt insert device error : %s", err)
		}
		fmt.Printf("mqtt insert device success : %s", device.DeviceNo)
	}
}

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
	fmt.Println("Connected to MQTT broker")
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
	fmt.Printf("Connection lost: %v\n", err)
}

func ConnectAndSubscribe() {
	// MQTT 配置
	opts := mqtt.NewClientOptions()
	opts.AddBroker(configration.Global.Mqtt.MqttAddr)   // MQTT 服务器地址
	opts.SetClientID("server-id")                       // 客户端 ID
	opts.SetUsername(configration.Global.Mqtt.UserName) // 用户名（如果有）
	opts.SetPassword(configration.Global.Mqtt.Password) // 密码（如果有）
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler

	// 创建 MQTT 客户端
	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}

	// 订阅主题
	topic := "autoclock/device_list/#"
	if token := client.Subscribe(topic, 1, nil); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	fmt.Printf("Subscribed to topic: %s\n", topic)

	// 保持连接
	for {
		time.Sleep(1 * time.Second)
	}
}
